import { ForwardedRef, forwardRef, useRef, useState } from "react";

interface BaseInputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "onChange"> {
    label: string;
    name: string;
    ref: ForwardedRef<HTMLInputElement>;
    onChange: (input: string) => void;
}

const CustomInput = forwardRef<HTMLInputElement, BaseInputProps>((props, ref) => {
    const { label, ...rest } = props;
    console.log("🚀 ~ rest:", rest);
    return (
        <div className="mb-4">
            <label htmlFor="custom-input" className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
            <input id="custom-input"
                ref={ref} className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-50"
                {...rest}
                onChange={(e) => props.onChange(e.target.value)} >
            </input>
        </div>
    );
});


const ForwardRefParent = () => {
    const inputRef = useRef<HTMLInputElement>(null);
    const [value, setValue] = useState('');

    const handleFocus = () => {
        inputRef.current?.focus();
    };

    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        alert(`Input value is: ${value}`);
    };

    return (
        <div className="container mx-auto p-8 max-w-md">
            <h1 className="text-2xl font-bold mb-6">React forwardRef 示例</h1>

            <form onSubmit={handleSubmit} className="space-y-4">
                <CustomInput
                    label="用户名"
                    name="leslie"
                    ref={inputRef}
                    onChange={(input) => setValue(input)}
                />

                <div className="flex space-x-3">
                    <button
                        type="button"
                        onClick={handleFocus}
                        className="px-4 py-2 bg-amber-700 hover:bg-blue-600  rounded-md transition-colors"
                    >
                        聚焦输入框
                    </button>
                    <button
                        type="submit"
                        className="px-4 py-2 bg-green-500 hover:bg-green-600  rounded-md transition-colors"
                    >
                        提交
                    </button>
                </div>
            </form>

            <div className="mt-6 p-4 bg-gray-50 rounded-lg border border-gray-200">
                <h3 className="font-medium text-gray-800 mb-2">关于 forwardRef</h3>
                <p className="text-sm text-gray-600">
                    这个示例展示了如何使用 React.forwardRef 将 ref 从父组件传递到子组件的 DOM 元素。
                    通过这种方式，父组件可以直接访问和操作子组件内部的 DOM 节点。
                </p>
            </div>
        </div>
    );
};

export default ForwardRefParent;